package com.hcbd.tdwt.base.bd;

import android.util.Log;

import com.hcbd.tdwt.MainApp;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.SerialPortManage;
import com.hcbd.tdwt.util.FileUtil;
import com.hcbd.tdwt.util.FileUtils;
import com.pangu.bdsdk2021.entity.terminaltwo.BDGGAInfo;
import com.pangu.bdsdk2021.entity.terminaltwo.BDGSVInfo;
import com.pangu.bdsdk2021.entity.terminaltwo.BDRMCInfo;
import com.pangu.bdsdk2021.util.BdCommonMethod;
import com.pangu.bdsdk2021.util.DataUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
// RN模块
public class RnssSerialPortManage extends SerialPortManage {

    private final String  sys_path ="/dev/ttyS1";///dev/ttyS0  波特率115200
    private BdManager bdManager;
    private String logName;

    public static final String TYPE_01="01";
    public static final String TYPE_12="12";
    public static final String TYPE_13="13";
    public static final String TYPE_H_01="h01";
    public static final String TYPE_H_02="h12";
    public static final String TYPE_H_03="h13";
    public static final String ANTENNA_I1="out 19 0";
    public static final String ANTENNA_I2="out 20 0";
    public static final String ANTENNA_E1="out 19 1";
    public static final String ANTENNA_E2="out 20 1";
    private final String on_off_power_path="sys/devices/platform/pinctrl@1000b000/mt_gpio";  // 控制节点

    private static  RnssSerialPortManage rnssSerialPortManage;
    public static RnssSerialPortManage getInstance() {
        if (rnssSerialPortManage == null) {
            rnssSerialPortManage = new RnssSerialPortManage();
        }
        return rnssSerialPortManage;
    }
    public RnssSerialPortManage(){
        bdManager=BdManager.getInstance();
        logPath= FileUtil.getLogFile();
        logName="rnss";
    }
    @Override
    protected void tailoringInstruction(String stringData){
        //查找校验和
        int xorIndex = stringData.indexOf("*");
        //<语句类型标识>, <数据字段1>,<数据字段2>, ..., <数据字段n>
        if (xorIndex != -1) {
            stringData = stringData.substring(0, xorIndex);
        }
        String []data=stringData.split("\\$");
        for(String str:data){
            onReceived(str);
        }
    }

    @Override
    public void onReceived(String stringData) {
        int source = MainApp.getInstance().sp.getAttributeInt(Constant.DATA_SOURCES);
        if(source==-1){
            return;
        }
        if("".equals(stringData)){
            return;
        }
//        FileUtils.writeFile(FileUtil.getLogFile(),logName,stringData);  // 不记rn
        String[] values = stringData.split(",", -1);
        Log.i(TAG, "接收到RN数据: "+ Arrays.toString(values));
        if (stringData.contains("GSV")) {//授权信息
            onReceiveBDGSVInfo(values);
        }else if(stringData.contains("GGA")){
            onReceiveBDGGAInfo(values);
        }else if(stringData.contains("RMC")){
            onReceiveBDRMCInfo(values);
        }
    }
    public void sendBytes(byte[] paramArrayOfByte, int size){
        //发送数据到北斗模块
        try {
            byte[] sendByte = new byte[size];
            if (paramArrayOfByte == null || paramArrayOfByte.length < size) {
                return;
            }
            System.arraycopy(paramArrayOfByte, 0, sendByte, 0, size);
            String str=new String(sendByte,"GB2312");
            Log.e("sendBytes:",str);
            FileUtils.writeFile(logPath,"sned：--"+str);
            mOutputStream.write(sendByte);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 设置内外置天线
    public void setAntenna(String flag) {
        File file = new File(on_off_power_path);
        Log.e("power InfoMessage:", flag +" > "+on_off_power_path);
        FileUtils.writeFile(logPath,flag+"写入");
        try {
            if (!file.exists()) {
                Log.e("InfoMessage", on_off_power_path+" not found!!");
                FileUtils.writeFile("InfoMessage",flag+"BD /dev/bd1 not found!!");
                return;
            }
            FileOutputStream fos = new FileOutputStream(file, false);
            BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(fos));
            bfw.write(flag);
            bfw.close();
            fos.close();
            Log.e(TAG, "power success!!" );
        } catch (FileNotFoundException e) {
            Log.e(TAG, "BD FileNotFoundException!!" + e);
            FileUtils.writeFile("InfoMessage","BD FileNotFoundException!"+e);
        } catch (IOException e) {
            Log.e(TAG, "BD IOException!!" + e);
            FileUtils.writeFile("InfoMessage","BD FileNotFoundException!"+e);
        }
    }

    public boolean sendPCas04(String type) {
        byte Xor = 0;
        String icaContent ="$PCAS04,"+type+",0,0*";
        try {
            byte[] ICABytes = icaContent.getBytes("GB2312");
            byte[] ICAMsg = new byte[ICABytes.length + 4];

            for(int i = 1; i < ICABytes.length - 1; ++i) {
                Xor ^= ICABytes[i];
            }
            System.arraycopy(ICABytes, 0, ICAMsg, 0, ICABytes.length);
            ICAMsg[ICABytes.length] = (byte)this.byteToChar((byte)(Xor >> 4));
            ICAMsg[ICABytes.length + 1] = (byte)this.byteToChar((byte)(Xor & 15));
            ICAMsg[ICABytes.length + 2] = 13;
            ICAMsg[ICABytes.length + 3] = 10;
            this.sendBytes(ICAMsg, ICAMsg.length);
            return true;
        } catch (Exception var8) {
            Log.d("BDProtocol", "onPackageICAMsg change byte error!!! ");
            return false;
        }
    }
    public boolean sendPCAS00() {
        byte Xor = 0;
        String icaContent ="$PCAS00*";
        try {
            byte[] ICABytes = icaContent.getBytes("GB2312");
            byte[] ICAMsg = new byte[ICABytes.length + 4];

            for(int i = 1; i < ICABytes.length - 1; ++i) {
                Xor ^= ICABytes[i];
            }
            System.arraycopy(ICABytes, 0, ICAMsg, 0, ICABytes.length);
            ICAMsg[ICABytes.length] = (byte)this.byteToChar((byte)(Xor >> 4));
            ICAMsg[ICABytes.length + 1] = (byte)this.byteToChar((byte)(Xor & 15));
            ICAMsg[ICABytes.length + 2] = 13;
            ICAMsg[ICABytes.length + 3] = 10;
            this.sendBytes(ICAMsg, ICAMsg.length);
            return true;
        } catch (Exception var8) {
            Log.d("BDProtocol", "onPackageICAMsg change byte error!!! ");
            return false;
        }
    }





    public void sendCFGSYS(String type) {
        String icaContent ="$CFGSYS,"+type;
        String command = BdCommonMethod.castHanziStringToHexString(icaContent);
        command+="0D0A";
        byte[] data = DataUtil.castHexStringToByte(command);
        try{
            mOutputStream.write(data);
            FileUtils.writeFile(logPath,"sned：--"+icaContent);
        }catch (Exception e){
            e.printStackTrace();
            FileUtils.writeFile(logPath,"sned：--"+icaContent+"失败");
        }

    }
    public void sendCFGSAVE() {
        String icaContent ="$CFGSAVE,h0F";
        String command = BdCommonMethod.castHanziStringToHexString(icaContent);
        command+="0D0A";
        byte[] data = DataUtil.castHexStringToByte(command);
        try{
            mOutputStream.write(data);
            FileUtils.writeFile(logPath,"sned：--"+icaContent);
        }catch (Exception e){
            e.printStackTrace();
            FileUtils.writeFile(logPath,"sned：--"+icaContent+"失败");
        }
    }
    void onReceiveBDGSVInfo(String[] instrucs){
        BDGSVInfo bdgsvInfo=new BDGSVInfo();
        if (instrucs.length >= 20) {
            bdgsvInfo.satellitesType = instrucs[0];
            bdgsvInfo.totalNumber = instrucs[1];
            bdgsvInfo.statementNumber = instrucs[2];
            bdgsvInfo.satellitesNumber = instrucs[3];
            bdgsvInfo.sv1 = instrucs[4];
            bdgsvInfo.elv1 = instrucs[5];
            bdgsvInfo.azl1 = instrucs[6];
            bdgsvInfo.cno1 = instrucs[7];
            bdgsvInfo.sv2 = instrucs[8];
            bdgsvInfo.elv2 = instrucs[9];
            bdgsvInfo.azl2 = instrucs[10];
            bdgsvInfo.cno2 = instrucs[11];
            bdgsvInfo.sv3 = instrucs[12];
            bdgsvInfo.elv3 = instrucs[13];
            bdgsvInfo.azl3 = instrucs[14];
            bdgsvInfo.cno3 = instrucs[15];
            bdgsvInfo.sv4 = instrucs[16];
            bdgsvInfo.elv4 = instrucs[17];
            bdgsvInfo.azl4 = instrucs[18];
            bdgsvInfo.cno4 = instrucs[19];
            bdManager.onGSVInfo(bdgsvInfo);
        }

    }

    void onReceiveBDGGAInfo(String[] instrucs){
        BDGGAInfo info=new BDGGAInfo();
        if (instrucs.length >= 15) {
            if (instrucs[6].equals("0")) return;  // 0 就是无效定位，不要
            info.positioningMoment = instrucs[1];
            info.latitude = instrucs[2];
            info.latitudeDirection = instrucs[3];
            info.longitude = instrucs[4];
            info.longitudeDirection = instrucs[5];
            info.statusIndication = instrucs[6];
            info.visibleSatellite = instrucs[7];
            info.hdop = instrucs[8];
            info.antennaHeight = instrucs[9];
            info.antennaHeightUnit = instrucs[10];
            info.abnormalElevation = instrucs[11];
            info.satelliteSigLockStatusUnit = instrucs[12];
            info.differentialDataAge = instrucs[13];
            info.differentialStationID = instrucs[14];
            bdManager.onGGAInfo(info);
//            MainApp.getInstance().showMsg("当前gga经纬度："+instrucs[4]+"/"+instrucs[2]);
        }
    }

    // BDRMC, 055321.00, A, 2309.33795, N, 11330.01557, E, 3.17, , 140324, , , A, V
    void onReceiveBDRMCInfo(String[] instrucs){
        BDRMCInfo info=new BDRMCInfo();
        if (instrucs.length >= 12) {
            info.utcTime = instrucs[1];
            info.positionStatus = instrucs[2];
            info.latitude = instrucs[3];
            info.latitudeDirection = instrucs[4];
            info.longitude = instrucs[5];
            info.longitudeDirection = instrucs[6];
            info.groundSpeed = instrucs[7];
            info.groundHeading = instrucs[8];
            info.date = instrucs[9];
            info.magneticDeclination = instrucs[10];
            info.magneticDeclinationDirection = instrucs[11];
            info.modeIndication = instrucs[12];
            bdManager.onRMDInfo(info);
        }
    }

    public void openXYSerialPort(){
        setBDPowerState("out 112 1");  // 电平转换使能3.3V
        setBDPowerState("out 25 1");  // MT6765控制北斗
        setBDPowerState("out 26 1");  // out 26 1 北斗模块5V电源
        openSerialPort(sys_path,baudRate);  // 打开RD模块
        try {
            Thread.sleep(120);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        setBDPowerState("out 18 1");  // 使能RNSS
        BdToolFactory.getBdSendBase().enableRN = true;
    }

    public void setBDPowerState(String flag) {
        File file = new File(on_off_power_path);
        Log.e("power InfoMessage:", flag +" > "+on_off_power_path);
        FileUtils.writeFile(logPath,flag+"写入");
        try {
            if (!file.exists()) {
                Log.e("InfoMessage", "BD /dev/bd1 not found!!");
                FileUtils.writeFile("InfoMessage",flag+"BD /dev/bd1 not found!!");
                return;
            }
            FileOutputStream fos = new FileOutputStream(file, false);
            BufferedWriter bfw = new BufferedWriter(new OutputStreamWriter(fos));
            bfw.write(flag);
            bfw.close();
            fos.close();
            Log.e(TAG, "power success!!" );
        } catch (FileNotFoundException e) {
            Log.e(TAG, "BD FileNotFoundException!!" + e);
            FileUtils.writeFile("InfoMessage","BD FileNotFoundException!"+e);
        } catch (IOException e) {
            Log.e(TAG, "BD IOException!!" + e);
            FileUtils.writeFile("InfoMessage","BD FileNotFoundException!"+e);
        }
    }

    public void closeXYSerialPort(){
        BdToolFactory.getBdSendBase().enableRN = false;
//        if(!BdToolFactory.getBdSendBase().enableRD){
//            setBDPowerState("out 112 0");
//            setBDPowerState("out 25 0");
//            setBDPowerState("out 26 0");
//        }
        //关闭串口
        closeSerialPort();
        FileUtils.writeFile(logPath,sys_path+"：--串口已关闭!");
    }
}
